<template>
  <div class="wrapper">
    <div class="reset-password">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="安全验证"></el-step>
        <el-step title="设置新密码"></el-step>
        <el-step title="设置成功"></el-step>
      </el-steps>
      <!-- 安全验证 -->
      <el-form class="v-form" v-if="currentStep === 0" :model="verifyForm" ref="verifyForm" :rules="verifyFormRules">
        <el-form-item class="v-form-item pre-icon" prop="mobile">
          <i class="icon-mobile"></i>
          <el-input v-model="verifyForm.mobile" size="medium" placeholder="请输入手机号码" maxlength="11" clearable></el-input>
        </el-form-item>
        <el-form-item class="v-form-item" prop="imgCode">
          <el-input v-model="verifyForm.imgCode" size="medium" placeholder="请输入图片验证码" maxlength="4" @blur="checkImgCode" clearable>
            <template slot="append">
              <img :src="imgCodeSrc" class="image-code" @click="getImgCode">
            </template>
          </el-input>
          <p class="v-valid-tips success" v-show="isImgCodeRight">验证码输入正确</p>
        </el-form-item>
        <el-form-item class="v-form-item" prop="msgCode">
          <el-input v-model="verifyForm.msgCode" size="medium" placeholder="请输入短信验证码" maxlength="6" clearable>
            <template slot="append">
              <button type="button" class="inner-btn" :class="{'disabled': sendMsg}" :disabled="sendMsg" @click="sendMsgCode">{{msgTip}}</button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <!-- 设置新密码 -->
      <el-form class="v-form" v-if="currentStep === 1" :model="paswForm" ref="paswForm" :rules="paswFormRules">
        <el-form-item class="v-form-item pre-icon" prop="password">
          <i class="icon-lock"></i>
          <el-input v-model="paswForm.password" type="password" size="medium" placeholder="请设置6-20位字母或数字组合的新密码" maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item class="v-form-item pre-icon" prop="confirmPassword">
          <i class="icon-lock"></i>
          <el-input v-model="paswForm.confirmPassword" type="password" size="medium" placeholder="请确认新密码" maxlength="20" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 下一步按钮 -->
      <div class="step-btn" @click="next">{{btnTxt}}</div>
    </div>
  </div>
</template>

<script>
import Md5 from 'js-md5'
export default {
  data () {
    return {
      currentStep: 0,
      verifyForm: {
        mobile: '',
        imgCode: '',
        msgCode: '',
        operateType: 'resetPsw'
      },
      verifyFormRules: {
        mobile: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入手机号码'))
              } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                callback(new Error('您输入手机号码不正确'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        imgCode: [
          {required: true, message: '请输入图片验证码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!/^[a-zA-z0-9]{4}$/.test(value)) {
                callback(new Error('图片验证码有误，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        msgCode: [
          {required: true, message: '请输入短信验证码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!/^[a-zA-z0-9]{6}$/.test(value)) {
                callback(new Error('短信验证码有误，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      paswForm: {
        password: '',
        confirmPassword: ''
      },
      paswFormRules: {
        password: [
          {
            validator: (rule, value, callback) => {
              if (value.length < 6) {
                callback(new Error('密码应不少于6个字符'))
              } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}/.test(value)) {
                callback(new Error('密码必须由数字和字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        confirmPassword: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.paswForm.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      imgCodeSrc: this.$api + '/pc/sys/verify', // 图片验证码
      isImgCodeRight: false, // 图片验证码是否正确
      sendMsg: false, // 是否已发送短信验证码
      msgTip: '获取验证码', // 获取短信验证码提示语
      time: 0 // 重新获取验证码时间，单位: s
    }
  },
  mounted () {
    this.$store.commit('setHeaderTit', '忘记密码')
  },
  computed: {
    btnTxt () {
      if (this.currentStep > 1) {
        return '确定'
      } else {
        return '下一步'
      }
    }
  },
  methods: {
    // 下一步
    next () {
      switch (this.currentStep) {
        case 0:
          this.$refs.verifyForm.validate(valid => {
            if (valid) {
              this.$http.post(this.$api + '/pc/sys/checkVcode', {
                mobile: this.verifyForm.mobile,
                vcode: this.verifyForm.msgCode
              }).then(res => {
                if (res.responseCode === '0000') {
                  this.currentStep++
                  this.$nextTick(() => {
                    this.$refs.paswForm.resetFields()
                  })
                } else {
                  this.$message.error({
                    duration: this.$store.state.duration,
                    message: res.responseMsg
                  })
                }
              })
            } else {
              return false
            }
          })
          break
        case 1:
          this.$refs.paswForm.validate(valid => {
            if (valid) {
              this.$http.post(this.$api + '/pc/customer/resetPsw', {
                mobile: this.verifyForm.mobile,
                newPsw: Md5(this.paswForm.password)
              }).then(res => {
                if (res.responseCode === '0000') {
                  this.currentStep++
                } else {
                  this.$message.error({
                    duration: this.$store.state.duration,
                    message: res.responseMsg
                  })
                }
              })
            } else {
              return false
            }
          })
          break
        case 2:
          this.$router.push('/login')
          break
      }
    },
    // 获取图片验证码
    getImgCode () {
      let time = new Date()
      this.imgCodeSrc = this.$api + '/pc/sys/verify?time=' + Date.parse(time)
      this.isImgCodeRight = false
      if (this.$refs.verifyForm) {
        this.$refs.verifyForm.$children[1].resetField()
      }
    },
    // 检查图片验证码是否正确
    checkImgCode () {
      if (this.verifyForm.imgCode) {
        this.$http.post(this.$api + '/pc/sys/checkImgCode', {
          imgCode: this.verifyForm.imgCode
        }).then(res => {
          if (res.responseCode === '0000') {
            this.isImgCodeRight = true
          } else {
            this.isImgCodeRight = false
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        return false
      }
    },
    // 发送短信验证码
    sendMsgCode () {
      if (this.verifyForm.mobile && this.isImgCodeRight && /^1[3456789]\d{9}$/.test(this.verifyForm.mobile)) {
        this.$http.post(this.$api + '/pc/sys/sendMsg', {
          mobile: this.verifyForm.mobile,
          operateType: this.verifyForm.operateType
        }).then(res => {
          if (res.responseCode === '0000') {
            this.sendMsg = true
            this.$message({
              type: 'success',
              message: '验证码已发送，请注意查收'
            })
          } else {
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        this.$message.error('请输入正确的手机号码和图片验证码')
      }
    }
  },
  watch: {
    'verifyForm.imgCode': function () {
      this.isImgCodeRight = false
    },
    // 检测到已发送短信验证码禁用发送按钮并开始倒计时
    'sendMsg': function () {
      if (this.sendMsg) {
        this.time = 60
      } else {
        return false
      }
    },
    // 短信验证码倒计时
    'time': function () {
      if (this.sendMsg) {
        if (this.time === 0) {
          this.sendMsg = false
          this.msgTip = '获取验证码'
        } else {
          setTimeout(() => {
            this.time--
            this.msgTip = '重新发送(' + this.time + ')'
          }, 1000)
        }
      } else {
        this.msgTip = '获取验证码'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/basic.scss';
.wrapper {
  padding: 60px 0 100px;
  background: #f7f7f7;
}
.reset-password {
  margin: 0 auto;
  width: 600px;
  .v-form {
    padding: 50px 140px 0;
  }
  .image-code {
    display: block;
    width: 99px;
    height: 34px;
    cursor: pointer;
  }
  .step-btn {
    margin: 10px auto;
    width: 320px;
    height: 45px;
    line-height: 45px;
    font-size: $fz_16;
    text-align: center;
    letter-spacing: 0.5em;
    color: #ffffff;
    background: $green;
    cursor: pointer;
    transition: all 0.3s;
    &:hover {
      background: $green_l;
    }
  }
}
</style>
